package com.yangwudongxi.sqlloghelper.controller;

import com.yangwudongxi.sqlloghelper.dto.ApiResponse;
import com.yangwudongxi.sqlloghelper.dto.DatabaseConfig;
import com.yangwudongxi.sqlloghelper.dto.QueryRequest;
import com.yangwudongxi.sqlloghelper.dto.QueryResult;
import com.yangwudongxi.sqlloghelper.dto.TableCommentsRequest;
import com.yangwudongxi.sqlloghelper.service.DatabaseQueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * SQL查询控制器
 *
 * @author 氧屋东西
 */
@Slf4j
@RestController
@RequestMapping("/sql")
@RequiredArgsConstructor
@Validated
public class SqlQueryController {
    
    private final DatabaseQueryService databaseQueryService;
    
    /**
     * 执行SQL查询
     */
    @PostMapping("/query")
    public ApiResponse<QueryResult> executeQuery(@RequestBody @Valid QueryRequest request) {
        log.info("执行SQL查询：{}", request.getSql());
        
        try {
            QueryResult result = databaseQueryService.executeQuery(
                request.getSql(), 
                request.getDbConfig()
            );
            
            return ApiResponse.success("查询成功", result);
        } catch (Exception e) {
            log.error("SQL查询失败", e);
            return ApiResponse.error("查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 测试数据库连接
     */
    @PostMapping("/test-connection")
    public ApiResponse<Boolean> testConnection(@RequestBody @Valid DatabaseConfig dbConfig) {
        log.info("测试数据库连接：{}:{}", dbConfig.getHost(), dbConfig.getPort());
        
        try {
            boolean connected = databaseQueryService.testConnection(dbConfig);
            
            if (connected) {
                return ApiResponse.success("数据库连接成功", true);
            } else {
                return ApiResponse.error("数据库连接失败");
            }
        } catch (Exception e) {
            log.error("数据库连接测试失败", e);
            return ApiResponse.error("连接测试失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取表注释
     */
    @PostMapping("/table-comments")
    public ApiResponse<Map<String, String>> getTableComments(@RequestBody @Valid TableCommentsRequest request) {
        log.info("获取表注释，表数量：{}", request.getTableNames().size());
        
        try {
            Map<String, String> tableComments = databaseQueryService.getTableComments(
                request.getTableNames(),
                request.getDbConfig()
            );
            
            return ApiResponse.success("获取表注释成功", tableComments);
        } catch (Exception e) {
            log.error("获取表注释失败", e);
            return ApiResponse.error("获取表注释失败：" + e.getMessage());
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ApiResponse<String> health() {
        return ApiResponse.success("服务正常运行");
    }
}